package io.tij;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class GetChannel {
	private final static int BSIZE = 1024;
	public static void main(String[] args) throws Exception{

		// Create data file
		File file = new File("data.txt");
		if(!file.exists())
			file.createNewFile();
		
		// write a file
		FileChannel fc = new FileOutputStream(file).getChannel();
		fc.write(ByteBuffer.wrap("Some text".getBytes()));
		fc.close();
		
		// Add to end of the file:
		fc = new RandomAccessFile(file, "rw").getChannel();
		fc.position(fc.size()); // Move to the end of the file
		fc.write(ByteBuffer.wrap("Some more".getBytes()));
		fc.close();
		
		// Read the file
		fc = new FileInputStream(file).getChannel();
		ByteBuffer bf = ByteBuffer.allocate(BSIZE);
		fc.read(bf);
		bf.flip();
		while(bf.hasRemaining())
			System.out.print((char)bf.get());
	}
}
